//
//  HMUserAccount.swift
//  weibo10
//
//  Created by mac on 15/10/19.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

class HMUserAccount: NSObject, NSCoding{
    /// 用于调用access_token，接口获取授权后的access token
    var access_token: String?
    /// access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval = 0{
        didSet{
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var expiresDate: NSDate?
    /// 当前授权用户的UID
    var uid: String?
    /// 用户昵称
    var screen_name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    init(dict:[String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    override var description:String{
        let array = ["access_token","expires_in","expiresDate","uid","screen_name","avatar_large"]
        return dictionaryWithValuesForKeys(array).description
    }
    // MARK -归档保存
    func saveUserAccount(){
        // 路径
        var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        // 拼接路径
        path = (path as NSString).stringByAppendingPathComponent("account.plist")
        print(path)
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    // MARK -实现归档方法
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
    }
    // MARK - 解档
    required init?(coder aDecoder: NSCoder) {
       self.access_token = aDecoder.decodeObjectForKey("access_token") as? String
        self.avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        self.uid = aDecoder.decodeObjectForKey("uid") as? String
        self.screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        self.expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
    }
    
}
